/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.cx1.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.apache.commons.lang.StringUtils;
import org.cx1.dao.api.IUserDao;
import org.cx1.dao.impl.UserDao;
import org.cx1.model.Listing;
import org.cx1.model.User;
import org.cx1.model.ds.MockDS;
import org.cx1.model.utils.ServiceResponse;
import org.cx1.service.api.IListingService;
import org.cx1.service.api.IUserService;
import org.cx1.service.utils.IDGenerator;

/**
 *
 * @author ECH
 */
public class DUserService implements IUserService {

    private IUserDao userDao = new UserDao();
    
    @Override
    public ServiceResponse<String> create(User user) {
        ServiceResponse<String> response = new ServiceResponse<String>();
        String id = null;        
        try {            
            boolean verified = true;
            //CX: check required fields
            if (StringUtils.isEmpty(user.getEmail())) {
                response.setMessage("Your email is required.");
                verified = false;
            }
            if (StringUtils.isEmpty(user.getFirstName())) {
                response.setMessage("Your name is required.");
                verified = false;
            }
            if (StringUtils.isEmpty(user.getLastName())) {
                response.setMessage("Your name is required.");
                verified = false;
            }
            if (StringUtils.isEmpty(user.getPassword())) {
                response.setMessage("A password is required.");
                verified = false;
            }
            //CX: check existing email
            if (emailExists(user.getEmail())) {
                response.setMessage("Email is already existing.");
                verified = false;
            }
            
            if (verified) {                
                User entry = new User();
                
                id = user.getId();
                if (StringUtils.isEmpty(id)) {
                    id = IDGenerator.generateID();      
                }

                entry.setId(id);              
                entry.setEmail(user.getEmail());
                entry.setPassword(user.getPassword());

                entry.setName(user.getName());
                entry.setFirstName(user.getFirstName());
                entry.setLastName(user.getLastName());
                
                entry.setTitle(user.getTitle());
                entry.setDescription(user.getDescription());
                entry.setNotes(user.getNotes());

                //CX: contact details
                
                entry.setEmailPrimary(user.getEmail());
                entry.setEmailSecondary(user.getEmailSecondary());
                
                entry.setMobilePrimary(user.getMobilePrimary());
                entry.setMobileSecondary(user.getMobileSecondary());
                
                entry.setLandlinePrimary(user.getLandlinePrimary());
                entry.setLandlineSecondary(user.getLandlineSecondary());     
                
                entry.setActive(true);
                entry.setDateCreated(new Date());
                entry.setDateModified(new Date());
                
                userDao.add(entry);
                
                response.setResponse(id);            
            }
            response.setSuccessful(true);            
        } 
        catch (Exception ex) {
            response.setResponse(null);
            response.setSuccessful(false);
            response.setMessage(ex.getMessage());
            response.setException(ex);
            ex.printStackTrace();            
        }
        return response;
    }

    @Override
    public ServiceResponse<List<User>> readAll(int offset, int limit) {
        ServiceResponse<List<User>> response = new ServiceResponse<List<User>>();
        List<User> users = new ArrayList<User>();
        try {       
            List<User> records = userDao.getAll();
            if (records != null && records.size() > 0) {
                if (offset == 0 && limit == 0) {
                    users.addAll(records);
                }
                else if (offset < records.size() && limit < records.size()) {
                    users.addAll( records.subList(offset, limit) );
                }              
            }            
            response.setResponse(users);
            response.setSuccessful(true);            
        } 
        catch (Exception ex) {
            response.setResponse(null);
            response.setSuccessful(false);
            response.setMessage(ex.getMessage());
            response.setException(ex);
            ex.printStackTrace();            
        }
        return response; 
    }

    @Override
    public ServiceResponse<User> read(String id) {
        ServiceResponse<User> response = new ServiceResponse<User>();
        User user = null;
        try {            
            user = userDao.getById(id);     
            response.setResponse(user);
            response.setSuccessful(true);            
        } 
        catch (Exception ex) {
            response.setResponse(null);
            response.setSuccessful(false);
            response.setMessage(ex.getMessage());
            response.setException(ex);
            ex.printStackTrace();            
        }
        return response; 
    }

    @Override
    public ServiceResponse<Boolean> update(User user) {
        ServiceResponse<Boolean> response = new ServiceResponse<Boolean>();
        boolean success = false;
        try {            
            String targetID = user.getId();
            User targetUser = this.read(targetID).getResponse();

            //CX: update dabase record
            if (targetUser != null) {
                targetUser.setTitle(user.getTitle());
                targetUser.setDescription(user.getDescription());
                targetUser.setNotes(user.getNotes());
                
                targetUser.setEmail(user.getEmail());
                targetUser.setPassword(user.getPassword());

                targetUser.setName( user.getName() );
                targetUser.setFirstName( user.getFirstName() );
                targetUser.setLastName( user.getLastName() );
                
                targetUser.setEmailPrimary(user.getEmail());
                targetUser.setEmailSecondary(user.getEmailSecondary());
                targetUser.setMobilePrimary(user.getMobilePrimary());
                targetUser.setMobileSecondary(user.getMobileSecondary());
                targetUser.setLandlinePrimary(user.getLandlinePrimary());
                targetUser.setLandlineSecondary(user.getLandlineSecondary());

                targetUser.setLastLogin(user.getLastLogin());
                
                targetUser.setDateModified(new Date());    
                
                userDao.update(targetUser);
                success = true;
            }                
            response.setResponse(success);
            response.setSuccessful(true);            
        } 
        catch (Exception ex) {
            response.setResponse(null);
            response.setSuccessful(false);
            response.setMessage(ex.getMessage());
            response.setException(ex);
            ex.printStackTrace();            
        }
        return response; 
    }

    @Override
    public ServiceResponse<Boolean> delete(String id) {
        ServiceResponse<Boolean> response = new ServiceResponse<Boolean>();
        boolean success = false;
        try {            
            userDao.deleteById(id);
            success = true;
            response.setResponse(success);
            response.setSuccessful(true);            
        } 
        catch (Exception ex) {
            response.setResponse(null);
            response.setSuccessful(false);
            response.setMessage(ex.getMessage());
            response.setException(ex);
            ex.printStackTrace();            
        }
        return response; 
    }

    @Override
    public ServiceResponse<Boolean> refreshLastLogin(String id) {
        ServiceResponse<Boolean> response = new ServiceResponse<Boolean>();
        boolean success = false;
        try {            
            User record = this.read(id).getResponse();
            if (StringUtils.equalsIgnoreCase(record.getId(), id)) {
                record.setLastLogin(new Date());
                this.update(record);
                success = true;
            }  
            response.setResponse(success);
            response.setSuccessful(true);            
        } 
        catch (Exception ex) {
            response.setResponse(null);
            response.setSuccessful(false);
            response.setMessage(ex.getMessage());
            response.setException(ex);
            ex.printStackTrace();            
        }
        return response; 
    }

    @Override
    public ServiceResponse<List<User>> readDormatUsers() {
        ServiceResponse<List<User>> response = new ServiceResponse<List<User>>();
        List<User> users = new ArrayList<User>();        
        try {                 
            response.setResponse(users);
            response.setSuccessful(true);            
        } 
        catch (Exception ex) {
            response.setResponse(null);
            response.setSuccessful(false);
            response.setMessage(ex.getMessage());
            response.setException(ex);
            ex.printStackTrace();            
        }
        return response;
    }
    
    private boolean emailExists(String email) {
        boolean exists = false;
        try {
            ServiceResponse<List<User>> sr1 = this.readAll(0, 0);
            if (sr1.isSuccessful() && sr1.getResponse() != null && sr1.getResponse().size() > 0) {
                for (User user : sr1.getResponse()) {
                    if (StringUtils.equals(user.getEmail().trim(), email.trim())) {
                        exists = true;
                    }
                }
            }            
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return exists;
    }
    
    
    
    public ServiceResponse<String> createImport(User user) {
        ServiceResponse<String> response = new ServiceResponse<String>();
        String id = null;        
        try {            
            boolean verified = true;
            //CX: check required fields
            if (StringUtils.isEmpty(user.getEmail())) {
                response.setMessage("Your email is required.");
                verified = false;
            }
            if (StringUtils.isEmpty(user.getFirstName())) {
                response.setMessage("Your name is required.");
                verified = false;
            }
            if (StringUtils.isEmpty(user.getLastName())) {
                response.setMessage("Your name is required.");
                verified = false;
            }
            if (StringUtils.isEmpty(user.getPassword())) {
                response.setMessage("A password is required.");
                verified = false;
            }
            //CX: check existing email
            if (emailExists(user.getEmail())) {
                response.setMessage("Email is already existing.");
                verified = false;
            }
            
            if (verified) {                
                User entry = new User();
                
                id = user.getId();

                entry.setId(id);              
                entry.setEmail(user.getEmail());
                entry.setPassword(user.getPassword());

                entry.setName(user.getName());
                entry.setFirstName(user.getFirstName());
                entry.setLastName(user.getLastName());
                
                entry.setTitle(user.getTitle());
                entry.setDescription(user.getDescription());
                entry.setNotes(user.getNotes());

                //CX: contact details
                
                entry.setEmailPrimary(user.getEmail());
                entry.setEmailSecondary(user.getEmailSecondary());
                
                entry.setMobilePrimary(user.getMobilePrimary());
                entry.setMobileSecondary(user.getMobileSecondary());
                
                entry.setLandlinePrimary(user.getLandlinePrimary());
                entry.setLandlineSecondary(user.getLandlineSecondary());     
                
                entry.setActive(user.isActive());
                entry.setDateCreated(user.getDateCreated());
                entry.setDateModified(user.getDateModified());
                
                userDao.add(entry);
                
                response.setResponse(id);            
            }
            response.setSuccessful(true);            
        } 
        catch (Exception ex) {
            response.setResponse(null);
            response.setSuccessful(false);
            response.setMessage(ex.getMessage());
            response.setException(ex);
            ex.printStackTrace();            
        }
        return response;
    }
        
    @Override
    public ServiceResponse<User> readByEmail(String email) {
        ServiceResponse<User> response = new ServiceResponse<User>();
        User user = null;
        try {            
            user = userDao.getByEmail(email);
            response.setResponse(user);
            response.setSuccessful(true);            
        } 
        catch (Exception ex) {
            response.setResponse(null);
            response.setSuccessful(false);
            response.setMessage(ex.getMessage());
            response.setException(ex);
            ex.printStackTrace();            
        }
        return response; 
    }
    
    public static void main(String[] argv) {
        /*
        IUserService userService = new DUserService();
        
        for (int i = 1; i < 11; i++) {
            User user = new User();
            user.setEmail(i + "test@email.com");
            user.setPassword("test1234");
            user.setFirstName("Test");
            user.setLastName("User");
            userService.create(user);            
        }
        */
        
        /*
        ServiceResponse<List<User>> response1 = userService.readAll(0, 0);
        List<User> users = response1.getResponse();
        if (users != null && users.size() > 0) {
            for (User user : users) {
                System.out.println("CX: " + user.getEmail() + " " + user.getId());
            }
        }
        */
        
        /*
        ServiceResponse<User> response1 = userService.read("a88d9c8074");
        User user = response1.getResponse();
        if (user != null) {
            System.out.println("CX: " + user.getEmail());
            System.out.println("CX: " + user.getPassword());
        }
        */
        
        /*
        ServiceResponse<User> response1 = userService.read("a88d9c8074");
        User user = response1.getResponse();
        if (user != null) {
            user.setEmail("untest@email.com");
            userService.update(user);
            
            ServiceResponse<User> response2 = userService.read("a88d9c8074");
            User user2 = response2.getResponse();
            if (user2 != null) {
                System.out.println("CX: " + user2.getEmail());
                System.out.println("CX: " + user2.getPassword());
            }
        }        
        */
               
        /*
        ServiceResponse<User> response1 = userService.read("17698e528");
        User user = response1.getResponse();
        if (user != null) {
            userService.delete(user.getId());
            
            ServiceResponse<User> response2 = userService.read("17698e528");
            User user2 = response2.getResponse();
            if (user2 == null) {
                System.out.println("CX: YAY!");
            }
        }
        */
        
        /*
        userService.refreshLastLogin("233f690220");
        ServiceResponse<User> response1 = userService.read("233f690220");
        User user = response1.getResponse();
        if (user != null) {
            System.out.println("CX: " + user.getEmail());
            System.out.println("CX: " + user.getLastLogin());
        }    
        */
    }
}
